<?php

namespace Dyadmin\Model;

use Think\Model;

class UserAgentProfitModel extends Model {

	//获取代理设置的列表
	public function get_agent_list($is_open=1,$is_vaild=1){
		
		$is_open = intval($is_open);
		$is_vaild = intval($is_vaild);
		if($is_vaild==1 || $is_vaild==0){
			$where['is_vaild'] = $is_vaild;//是否有效
		}
		if($is_open==1 || $is_open==0){
			$where['is_open'] = $is_open;//是否开启
		}
		$list = D('AreaAgent')->where($where)->order('id desc')->select();
		
		if(!$list){
			return false;
		}
		
		$result = array();
		foreach($list as $key=>$val){
			$result[$val['nid']] = $val;
		}
		
		return $result;
	}
	
	//根据nid 查找代理的名称
	public function get_name_by_nid($nid){
		if(empty($nid)){
			$nid = 'common';
		}
		$info = D('AreaAgent')->where(array('nid'=>$nid))->find();
		if(!$info){
			return '';
		}
		
		return $info['name'];
	}
        
        //检验并处理地区
	public function check_area($data= array()){
		//
		$country = array();//全国
		$province = array();//省份
		$city = array();//城市
		$error['city_name_empty'] = '市代理名称不能为空';
		$error['province_name_empty'] = '省代理名称不能为空';
		$error['name_error'] = '请选择正确的省市代理';
		$error['province_name_error'] = '请选择正确的省份【%s】';
		$error['city_name_error'] = '请选择正确的城市【%s】';
		$error['city_name_from_province_repeat'] = '市代理【%s】已有本城市所在省份【%s】代理';
		$error['nid_error'] = '代理等级错误或者为空';
		foreach($data as $key=>$val){
			if($val['agent_nid']=='country'){
				$country[] = $val['area_name'];
				break;
			}elseif($val['agent_nid']=='province'){
				$province[] = $val['area_name'];
			}elseif($val['agent_nid']=='city'){
				$city[] = $val['area_name'];
			}else{
				//return $error['nid_error']; 
				continue;
			}
			
			if(empty($val['area_name'])){
				return $error[$val['agent_nid'].'_name_empty'];
			}
		}
		
		//全国
		$area_name = '全国';
		if($country){
			$result = array('agent_nid'=>'country','area_name'=>$area_name);
			return $result;
		}
		
		//删除信息重复
		$province = array_flip($province);
		$city = array_flip($city);
		//var_dump($province);

		//获取所有有效省份
		$all = array();
		foreach($province as $key=>$val){
			$p_info = D('province')->field('code')->where(array('name'=>$key))->find();
			if(!$p_info){
				return printf($error['province_name_error'],$key);//continue;
			}
			$pcode_arr[$p_info['code']] = $key;
			$all[] = array('agent_nid'=>'province','area_name'=>$key);
		}
		
		//获取所有有效城市
		foreach($city as $key=>$val){
			$p_info = D('city')->field('province_code')->where(array('name'=>$key))->find();
			if(!$p_info){//无效的城市
				return printf($error['city_name_error'],$key); //continue;
			}
			$province_name = $pcode_arr[$p_info['province_code']];
			if(!empty($province_name)){//该城市代理 有此城市所在省份代理
				return printf($error['city_name_from_province_repeat'],$key,$province_name); //continue;	
				
			}
			$all[] = array('agent_nid'=>'city','area_name'=>$key);
		}
		
		if(count($all)){
			return $all;
		}
		return $error['name_error'];
	}
		
}